package com.itfreer.utils;

import java.io.IOException;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;

/**
 * JSON处理类
 */
public class JSONUtils {

	/***
	 * 将类型转换为字符串
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 */
	public static <T> String toJSONString(List<T> list) throws JsonGenerationException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		// 过滤对象的null属性.
		mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
		// 过滤map中的null值
		mapper.configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false);

		return mapper.writeValueAsString(list);
	}

	/***
	 * 将类型转换为字符串
	 * 
	 * @param object
	 * @return
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 */
	public static String toJSONString(Object object) throws JsonGenerationException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		// 过滤对象的null属性.
		mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
		// 过滤map中的null值
		mapper.configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false);

		return mapper.writeValueAsString(object);
	}

	/**
	 * 将JSON转换为对象
	 * @param <T>
	 * @param jsonObject
	 * @param beanClass
	 * @return
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 */
	public static <T> T toBean(String jsonObject, Class<T> beanClass) throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		// 过滤对象的null属性.
		mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
		// 过滤map中的null值
		mapper.configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false);
		mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

		T acc = mapper.readValue(jsonObject, beanClass);
		return acc;
	}
}